package cn.hs.ph.servlet;

import cn.hs.ph.dao.GoodsDao;
import cn.hs.ph.dao.impl.GoodsDaoImpl;
import cn.hs.ph.entity.Goods;
import cn.hs.ph.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        GoodsDao goodsDao = new GoodsDaoImpl();
        if ("selectAll".equals(action)){
            String pageNum = req.getParameter("pageNum");
            String pageSize = req.getParameter("pageSize");
            String goodsName = req.getParameter("goodsName");
            String goodsStatus = req.getParameter("goodsStatus");
            String shopName = req.getParameter("shopName");
            String startTime = req.getParameter("startTime");
            String endTime = req.getParameter("endTime");
            Map<String,String> map=new HashMap<>();
            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
            map.put("goodsName",goodsName);
            map.put("goodsStatus",goodsStatus);
            map.put("shopName",shopName);
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            List<Goods> list = goodsDao.selectAll(map);
            int count = goodsDao.selectCount(map);
            Map<String,Object> resMap = new HashMap<>();
            resMap.put("list",list);
            resMap.put("total",count);
            Result result = Result.success(resMap);
            resp.getWriter().write(JSON.toJSONString(result));
            //修改商品状态
        }else if("modify".equals(action)){
            //获取参数
            String id = req.getParameter("goodsId");
            int goodsId = Integer.parseInt(id);
            String status = req.getParameter("goodsStatus");
            int goodsStatus=0;
            if(status!=null && !"".equals(status)){
                goodsStatus=Integer.parseInt(status);
            }
            //封装参数
            Goods goods = new Goods();
            goods.setGoodsId(goodsId);
            goods.setGoodsStatus(goodsStatus);
            //调用修改方法
            int num = goodsDao.update(goods);
            Result res=null;
            if(num!=0){
                res=Result.success();
            }else {
                res=Result.error();
            }
            resp.getWriter().write(JSON.toJSONString(res));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
